# -*- coding: utf-8 -*-
import os
import sys
import copy
from datetime import datetime, timedelta
# add up one level dir into sys path
sys.path.append(os.path.abspath(os.path.dirname(
    os.path.dirname(os.path.dirname(__file__)))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'webservices.settings'
from common.es_core.es_interface import es_search_interface


start_time = datetime(2019, 8, 1)
end_time = datetime(2019, 9, 1)

user_device_map = {}

while start_time < end_time:
    print(start_time)
    dsl = {
        "query": {
            "bool": {
                "filter": [
                    {"range": {"_event_time": {"gte": start_time.timestamp(),
                                               "lt": (start_time + timedelta(days=1)).timestamp()}}},
                    {"term": {"_event_id": "active"}}
                ]
            }
        },
        "aggs": {
            "__": {
                "terms": {
                    "field": "_user_id",
                    "size": 50000
                },
                "aggs": {
                    "___": {
                        "terms": {
                            "field": "_ua.keyword",
                            "size": 1
                        }
                    }
                }
            },
        }
    }
    user_id = []
    for _ in range(0, 3):
        try:
            print('start query...')
            result = es_search_interface('dark3', dsl)
        except:
            pass
        else:
            break
    for e in result['aggregations']['__']['buckets']:
        if e['___']['buckets'][0]:
            user_device_map[e['key']] = e['___']['buckets'][0]['key']
    start_time += timedelta(days=1)
# print(user_device_map)
device_dct = {}

for _, user_device_type in user_device_map.items():
    user_device_type = user_device_type.split('|')[0]
    user_device_type = user_device_type.lower()
    device_dct.setdefault(user_device_type, 0)
    device_dct[user_device_type] += 1

with open('res.csv', 'a') as f:
    for k, v in device_dct.items():
        f.write(str(k) + ',' + str(v) + '\n')